package com.auth.project.cn.config;

import feign.Logger;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

@Slf4j
@Configuration
public class FeignMultipartSupportConfig {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    @Primary
    @Scope("prototype")
    public Encoder multipartFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }

    @Bean
    public feign.Logger.Level multipartLoggerLevel() {
        return Logger.Level.FULL;
    }

//    @Override
//    public void apply(RequestTemplate template) {
//        log.info("Feign client print apply:{}", MDC.get(TraceIDUtil.DEFAULT_TRACE_ID));
//        template.header(TraceIDUtil.DEFAULT_TRACE_ID, TraceIDUtil.getTraceId());
//    }

//    @Bean
//    @Order(-1)
//    public feign.Logger feignClientLogger() {
//        return new Slf4jLogger() {
//            private final org.slf4j.Logger logger = org.slf4j.LoggerFactory
//                    .getLogger(FeignMultipartSupportConfig.class);
//
//            @Override
//            protected void logRequest(String configKey, Level logLevel, Request request) {
//                logger.info("Feign client print logRequest configKey: {} , logLevel {} , request:{}, traceId:{}",
//                        configKey, logLevel, request, MDC.get(TraceIDUtil.DEFAULT_TRACE_ID));
//                super.logRequest(configKey, logLevel, request);
//            }
//
//            @Override
//            protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response,
//                    long elapsedTime) throws IOException {
//                logger.info("Feign client print logAndRebufferResponse configKey: {} , logLevel {} , request:{}",
//                        configKey, logLevel, response);
//                return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);
//            }
//
//            @Override
//            protected void log(String s, String s1, Object... objects) {
//                logger.info("Feign client print methodTag:{}", String.format(methodTag(s) + s1, objects));
//            }
//        };
//    }

    // 或者
    /*
     * @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(); }
     */
}